/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entidade.controller.JPA;

import entidade.controller.JPA.exceptions.NonexistentEntityException;
import entidade.controller.JPA.exceptions.RollbackFailureException;
import entidade.persistencia.Permissao;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidade.persistencia.TipoUsuario;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.UserTransaction;

/**
 *
 * @author victorinox
 */
public class PermissaoJpaController {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "globalimage2PU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Permissao permissao) throws RollbackFailureException, Exception {
        if (permissao.getTipoUsuarioCollection() == null) {
            permissao.setTipoUsuarioCollection(new ArrayList<TipoUsuario>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<TipoUsuario> attachedTipoUsuarioCollection = new ArrayList<TipoUsuario>();
            for (TipoUsuario tipoUsuarioCollectionTipoUsuarioToAttach : permissao.getTipoUsuarioCollection()) {
                tipoUsuarioCollectionTipoUsuarioToAttach = em.getReference(tipoUsuarioCollectionTipoUsuarioToAttach.getClass(), tipoUsuarioCollectionTipoUsuarioToAttach.getTipoUsuarioId());
                attachedTipoUsuarioCollection.add(tipoUsuarioCollectionTipoUsuarioToAttach);
            }
            permissao.setTipoUsuarioCollection(attachedTipoUsuarioCollection);
            em.persist(permissao);
            for (TipoUsuario tipoUsuarioCollectionTipoUsuario : permissao.getTipoUsuarioCollection()) {
                tipoUsuarioCollectionTipoUsuario.getPermissaoCollection().add(permissao);
                tipoUsuarioCollectionTipoUsuario = em.merge(tipoUsuarioCollectionTipoUsuario);
            }
            utx.commit();
            em.refresh(permissao);
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Permissao permissao) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Permissao persistentPermissao = em.find(Permissao.class, permissao.getPermissaoId());
            List<TipoUsuario> tipoUsuarioCollectionOld = persistentPermissao.getTipoUsuarioCollection();
            List<TipoUsuario> tipoUsuarioCollectionNew = permissao.getTipoUsuarioCollection();
            List<TipoUsuario> attachedTipoUsuarioCollectionNew = new ArrayList<TipoUsuario>();
            for (TipoUsuario tipoUsuarioCollectionNewTipoUsuarioToAttach : tipoUsuarioCollectionNew) {
                tipoUsuarioCollectionNewTipoUsuarioToAttach = em.getReference(tipoUsuarioCollectionNewTipoUsuarioToAttach.getClass(), tipoUsuarioCollectionNewTipoUsuarioToAttach.getTipoUsuarioId());
                attachedTipoUsuarioCollectionNew.add(tipoUsuarioCollectionNewTipoUsuarioToAttach);
            }
            tipoUsuarioCollectionNew = attachedTipoUsuarioCollectionNew;
            permissao.setTipoUsuarioCollection(tipoUsuarioCollectionNew);
            permissao = em.merge(permissao);
            for (TipoUsuario tipoUsuarioCollectionOldTipoUsuario : tipoUsuarioCollectionOld) {
                if (!tipoUsuarioCollectionNew.contains(tipoUsuarioCollectionOldTipoUsuario)) {
                    tipoUsuarioCollectionOldTipoUsuario.getPermissaoCollection().remove(permissao);
                    tipoUsuarioCollectionOldTipoUsuario = em.merge(tipoUsuarioCollectionOldTipoUsuario);
                }
            }
            for (TipoUsuario tipoUsuarioCollectionNewTipoUsuario : tipoUsuarioCollectionNew) {
                if (!tipoUsuarioCollectionOld.contains(tipoUsuarioCollectionNewTipoUsuario)) {
                    tipoUsuarioCollectionNewTipoUsuario.getPermissaoCollection().add(permissao);
                    tipoUsuarioCollectionNewTipoUsuario = em.merge(tipoUsuarioCollectionNewTipoUsuario);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = permissao.getPermissaoId();
                if (findPermissao(id) == null) {
                    throw new NonexistentEntityException("The permissao with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Permissao permissao;
            try {
                permissao = em.getReference(Permissao.class, id);
                permissao.getPermissaoId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The permissao with id " + id + " no longer exists.", enfe);
            }
            List<TipoUsuario> tipoUsuarioCollection = permissao.getTipoUsuarioCollection();
            for (TipoUsuario tipoUsuarioCollectionTipoUsuario : tipoUsuarioCollection) {
                tipoUsuarioCollectionTipoUsuario.getPermissaoCollection().remove(permissao);
                tipoUsuarioCollectionTipoUsuario = em.merge(tipoUsuarioCollectionTipoUsuario);
            }
            em.remove(permissao);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Permissao> findPermissaoEntities() {
        return findPermissaoEntities(true, -1, -1);
    }

    public List<Permissao> findPermissaoEntities(int maxResults, int firstResult) {
        return findPermissaoEntities(false, maxResults, firstResult);
    }

    private List<Permissao> findPermissaoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Permissao as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Permissao findPermissao(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Permissao.class, id);
        } finally {
            em.close();
        }
    }

    public Permissao findPermissaoByName(String pagina) {
        List<Permissao> perms = findPermissaoEntities();
        for (int i = 0; i < perms.size(); i++) {
            Permissao permissao = perms.get(i);
            if (permissao.getPagina().equals(pagina)) {
                return permissao;
            }
        }
        return null;
    }

    public int getPermissaoCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Permissao as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
